<template>
  <div class="store-container">
    <div class="filter-container">
      <el-input
        v-model="queryParams.name"
        placeholder="请输入门店名称"
        clearable
        style="width: 200px"
        class="filter-item"
        @keyup.enter="handleQuery"
      />
      <el-input
        v-model="queryParams.address"
        placeholder="请输入门店地址"
        clearable
        style="width: 200px"
        class="filter-item"
        @keyup.enter="handleQuery"
      />
      <el-select
        v-model="queryParams.status"
        placeholder="请选择状态"
        clearable
        style="width: 200px"
        class="filter-item"
      >
        <el-option
          v-for="item in statusOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" class="filter-item" @click="handleQuery">搜索</el-button>
      <el-button type="success" class="filter-item" @click="handleAdd">添加</el-button>
    </div>

    <el-table v-loading="loading" :data="storeList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="门店名称" width="180" />
      <el-table-column prop="address" label="门店地址" min-width="200" show-overflow-tooltip />
      <el-table-column prop="phone" label="联系电话" width="120" />
      <el-table-column prop="manager" label="负责人" width="120" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'info'">
            {{ scope.row.status === 0 ? '营业中' : '暂停营业' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="storeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="门店名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入门店名称" />
        </el-form-item>
        <el-form-item label="门店地址" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入门店地址" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="form.manager" placeholder="请输入负责人姓名" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">营业中</el-radio>
            <el-radio :label="1">暂停营业</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listStore, getStore, addStore, updateStore, delStore } from '@/api/store'

// 查询参数
const queryParams = reactive({
  name: '',
  address: '',
  status: undefined
})

// 门店列表数据
const storeList = ref([])
const loading = ref(false)

// 状态选项
const statusOptions = [
  { value: 0, label: '营业中' },
  { value: 1, label: '暂停营业' }
]

// 表单参考
const storeFormRef = ref()

// 表单数据
const form = reactive({
  id: undefined,
  name: '',
  address: '',
  phone: '',
  manager: '',
  status: 0
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '门店名称不能为空', trigger: 'blur' },
    { min: 2, max: 100, message: '门店名称长度必须在2到100个字符之间', trigger: 'blur' }
  ],
  address: [{ required: true, message: '门店地址不能为空', trigger: 'blur' }],
  phone: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^\d{3,4}-\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
  ],
  manager: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '请选择门店状态', trigger: 'change' }]
}

// 对话框信息
const dialog = reactive({
  visible: false,
  title: '',
  type: ''
})

// 获取门店列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listStore(queryParams)
    storeList.value = res || []
  } catch (error) {
    console.error('获取门店列表失败', error)
    ElMessage.error('获取门店列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  getList()
}

// 重置表单
const resetForm = () => {
  form.id = undefined
  form.name = ''
  form.address = ''
  form.phone = ''
  form.manager = ''
  form.status = 0
  storeFormRef.value?.resetFields()
}

// 添加按钮操作
const handleAdd = () => {
  resetForm()
  dialog.visible = true
  dialog.title = '添加门店'
  dialog.type = 'add'
}

// 修改按钮操作
const handleUpdate = async (row) => {
  resetForm()
  const id = row.id || row.id
  try {
    const res = await getStore(id)
    Object.assign(form, res)
    dialog.visible = true
    dialog.title = '修改门店'
    dialog.type = 'edit'
  } catch (error) {
    console.error('获取门店详情失败', error)
    ElMessage.error('获取门店详情失败')
  }
}

// 提交表单
const submitForm = async () => {
  storeFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          // 修改
          await updateStore(form)
          ElMessage.success('修改成功')
        } else {
          // 新增
          await addStore(form)
          ElMessage.success('新增成功')
        }
        dialog.visible = false
        getList()
      } catch (error) {
        console.error('提交表单失败', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  const id = row.id
  ElMessageBox.confirm('确认要删除该门店吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await delStore(id)
        getList()
        ElMessage.success('删除成功')
      } catch (error) {
        console.error('删除门店失败', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.store-container {
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-item {
  margin-right: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>
